<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 商店管理
 */
namespace app\allwin\controller;
use app\allwin\model\WorkerStoreOrder;
use app\allwin\model\AllwinStoreCate;
use app\allwin\model\AllwinStore;
use app\allwin\model\StoreStats;
use app\allwin\model\AllwinStoreChain;
use app\allwin\model\StoreWorker;
use app\allwin\model\AllwinUser;
use app\allwin\model\CouponUser;
use app\allwin\model\Order;
use app\allwin\model\MchIdUser;
use app\allwin\model\StoreUnion;
use app\allwin\model\AllwinUserAgent;
use app\allwin\model\Vip;
use app\allwin\model\AllwinConfig;
use app\common\facade\Inform;
use app\common\facade\AliApi;
use app\common\model\SystemUser;
use think\helper\Time;
use think\facade\Request;
use think\facade\Validate;

class Store extends Common{

    public function initialize(){
        parent::initialize();
        $this->assign('pathMaps',[['name'=>'商家管理','url'=>url("allwin/store/index")]]);
    }

    /**
     * 列表
     */
    public function index(int $types = 0){
        $condition   = [];
        $time      = Request::param('time/d',0);
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['create_time','>=',$start];
            $condition[] = ['create_time','<=',$end];
        }else{
            if($starttime){
                $condition[] = ['create_time','>=',strtotime($starttime)];
            }
            if($endtime){
                $condition[] = ['create_time','<=',strtotime($endtime)];
            }
        }
        $keyword = Request::param('keyword/s');
        if(!empty($keyword)){
            $condition[] = ['name','like','%'.$keyword.'%'];
        }
        $view['is_top_num'] = AllwinStore::where($this->mini_program)->where($condition)->where(['is_top' => 1])->count('is_top');
        $view['store_num']  = AllwinStore::where($this->mini_program)->where($condition)->count();
        $view['lock_num']   = AllwinStore::where($this->mini_program)->where($condition)->where(['is_lock' => 1])->count();
        $view['lists']      = AllwinStore::where($this->mini_program)->where($condition)->where(['is_lock' => $types ? 1 : 0])->order('is_top desc,sort desc,id desc')->paginate(20,false,['query' => ['types' => $types,'starttime' => $starttime,'endtime' => $endtime,'time'=>$time]]);
        $view['keyword']    = $keyword;
        $view['types']      = $types;
        $view['time']       = $time;
        $view['starttime']  = $starttime;
        $view['endtime']    = $endtime;
        return view()->assign($view);
    }

    /**
     * 选择商家列表
     */
    public function selectStore(){
        $condition = [];
        $condition[] = ['is_lock','=',0];
        $view['keyword'] = $this->request->param('keyword/s');
        if(!empty($view['keyword'])){
            $condition[] = ['name','like','%'.$view['keyword'].'%'];
        }
        $view['lists']  = AllwinStore::where($this->mini_program)->where($condition)->order('is_top desc,sort desc,id desc')->paginate(20);
        $view['input']  = $this->request->param('input');
        return view()->assign($view);
    }

    /**
     * 好店预览
     */
    public function review(int $id){
        $condition['id'] = $id;
        $view['info']   = AllwinStore::where($condition)->find();
        if(!$view['info']){
            $this->error('内容不存在');
        }
        $view['user']   = StoreWorker::where($this->mini_program)->where(['store_id' => $id])->order('id desc')->select();
        $view['manage'] = SystemUser::where($this->mini_program)->where(['id' => $view['info']['manage_uid']])->find();
        $stats = StoreStats::where($this->mini_program)->where(['store_id' => $id])->find();
        if(empty($stats)){
            $view['stats']['payment'] = money(0);
            $view['stats']['coupon']  = money(0);
            $view['stats']['card']    = money(0);
            $view['stats']['vip']     = money(0);
        }else{
            $view['stats']  = $stats;
        }
        $view['orders']  = Order::where($this->mini_program)->where(['store_id'=>$id,'state' => 1])->order('id desc')->paginate(10,false,['query' => ['id' => $id]]);
        return view()->assign($view);
    }
    
    /**
     * 添加
     */
    public function add(){
        if(request()->isAjax()){
            $data = [
                'id'                => 0,
                'member_miniapp_id' => $this->member_miniapp_id,
                'manage_uid'        => Request::param('manage_uid/d',0),
                'mch_id'            => Request::param('mch_id/d',0),
                'charges'           => Request::param('charges/d'),
                'cate_id'           => Request::param('cate_id/d',0),
                'cate_sid'          => Request::param('cate_sid/d',0),
                'code_id'           => Request::param('code_id/s'),
                'name'              => Request::param('name/s'),
                'type_text'         => Request::param('type_text/s'),
                'address'           => Request::param('address/s'),
                'longitude'         => Request::param('longitude/s'),
                'latitude'          => Request::param('latitude/s'),
                'telphone'          => Request::param('telphone/s'),
                'tips'              => Request::param('tips/s'),
                'tags'              => Request::param('tags/s'),
                'img'               => Request::param('img/s'),
                'imgs'              => Request::param('imgs/a'),
            ];
            $validate = $this->validate($data,'Store.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            if($data['charges'] > 0 && $data['charges'] <= 6){
                return json(['code'=>0,'msg'=>'抱歉~交易服务费禁止小于6‰']);
            }
            //判断付款码
            $result = AllwinStore::where(['code_id' => $data['code_id']])->find();
            if($result){
                return enjson(0,'付款编码已存在');
            }else{
                $rel = AllwinStoreChain::where(['code_id' => $data['code_id']])->find();
                if($rel){
                    return enjson(0,'付款编码已存在');
                }
            }
            //判断当前用户是否社群主
            if($data['manage_uid']){
                $agent = AllwinUserAgent::where(['uid' => $data['manage_uid']])->count();
                if($agent){
                    return json(['code'=>0,'msg'=>'当前用户是【社群主身份】,禁止绑定']);
                }
            }
            if(AllwinStore::edit($data)){
                return json(['code'=>200,'url'=>url('allwin/store/index',['cate_id' => $data['cate_id']]),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $view['cate']    = AllwinStoreCate::field('name,id')->where($this->mini_program)->where(['parent_id' => 0])->order('sort desc,id desc')->select();
            $view['setting'] = AllwinConfig::getConfig($this->member_miniapp_id);
            return view()->assign($view);
        }
    }

    //编辑
    public function edit(){
        if(request()->isAjax()){
            $data = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'id'                => Request::param('id/d'),
                'original_uid'      => Request::param('original_uid/d'),
                'original_mchid'    => Request::param('original_mchid/d'),
                'manage_uid'        => Request::param('manage_uid/d',0),
                'mch_id'            => Request::param('mch_id/d',0),
                'charges'           => Request::param('charges/d'),
                'cate_id'           => Request::param('cate_id/d',0),
                'cate_sid'          => Request::param('cate_sid/d',0),
                'name'              => Request::param('name/s'),
                'type_text'         => Request::param('type_text/s'),
                'address'           => Request::param('address/s'),
                'longitude'         => Request::param('longitude/s'),
                'latitude'          => Request::param('latitude/s'),
                'telphone'          => Request::param('telphone/s'),
                'tips'              => Request::param('tips/s'),
                'tags'              => Request::param('tags/s'),
                'img'               => Request::param('img/s'),
                'imgs'              => Request::param('imgs/a'),
            ];
            $validate = $this->validate($data,'Store.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            if($data['charges'] > 0 && $data['charges'] <= 6){
                return json(['code'=>0,'msg'=>'抱歉~交易服务费禁止小于6‰']);
            }
            //判断当前用户是否社群主
            if($data['manage_uid'] != $data['original_uid']){
                $agent = AllwinUserAgent::where(['uid' => $data['manage_uid']])->count();
                if($agent){
                    return json(['code'=>0,'msg'=>'绑定的好店店长是【社群主身份】,禁止绑定']);
                }
            }
            if(AllwinStore::edit($data)){
                if($data['mch_id'] != $data['original_mchid']){   //删除旧的分账接收方
                    MchIdUser::where($this->mini_program)->where(['store_id' => $data['id']])->delete();
                }
                return json(['code'=>200,'url'=>url('store/index',['cate_id' => $data['cate_id']]),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $info = AllwinStore::where($this->mini_program)->where(['id' => $this->request->param('id/d')])->find();
            if(!$info){
                $this->error("404 NOT FOUND");
            }
            $view['info']     = $info;
            $view['imgs']     = json_decode($info['imgs'],true);
            $view['cate']     = AllwinStoreCate::field('name,id')->where($this->mini_program)->where(['parent_id' => 0])->order('sort desc,id desc')->select();
            $view['cate_sub'] = AllwinStoreCate::field('name,id')->where(['parent_id' => $info['cate_id'],'member_miniapp_id' => $this->member_miniapp_id])->order('sort desc,id desc')->select();
            $view['setting']  = AllwinConfig::getConfig($this->member_miniapp_id);
            return view()->assign($view);
        }
    }
     

    /**
     * 排序
     */
    public function sort(){
        if(request()->isAjax()){
            $data = [
                'sort' => Request::param('sort/d'),
                'id'   => Request::param('id/d'),
            ];
            $validate = $this->validate($data,'Cate.sort');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result = AllwinStore::where(['id' => $data['id']])->update(['sort' => $data['sort']]);
            if($result){
                return json(['code'=>200,'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }
    }
    
    /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isTop(int $id){
        $result = AllwinStore::isTop($id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    } 

     /**
     * 置顶/取消
     * @param integer $id 用户ID
     */
    public function isLock(int $id){
        $result = AllwinStore::isLock($id,$this->member_miniapp_id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    } 
   
     /**
     * 设置营业状态
     * @param integer $id 用户ID
     */
    public function setState(int $id){
        $info = AllwinStore::where($this->mini_program)->where(['id' => $id])->find();
        if(!$info){
            return json(['code'=>0,'message'=>'未找到好店']);
        }
        $info->state = $info->state == 0 ? 1 : 0;
        $result = $info->save();
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    }
    

    //删除
    public function delete(int $id){
        $coupon = model('Coupon')->where($this->mini_program)->where(['store_id' => $id])->count();
        if($coupon){
            return json(['code'=>403,'msg'=>'请先删除好店优惠券']);
        }
        $couponUser =  CouponUser::where($this->mini_program)->where(['store_id' => $id])->count();
        if($couponUser){
            return json(['code'=>403,'msg'=>'请先删除用户已领优惠券']);
        }
        //判断分店
        $chain =  AllwinStoreChain::where($this->mini_program)->where(['store_id' => $id])->count();
        if($chain){
            return json(['code'=>403,'msg'=>'请先删除门店或收银台']);
        }
        //会员卡
        $count = model('Card')->where($this->mini_program)->where(['store_id' => $id])->count();
        if($count){
            return json(['code'=>403,'msg'=>'请先删除好店会员卡']);
        }
        StoreUnion::unionDelete(['store_id' => $id]);  //删除联合商家数据
        StoreWorker::where($this->mini_program)->where(['store_id' => $id])->delete();  //删除员工
        WorkerStoreOrder::where($this->mini_program)->where(['store_id' => $id])->delete();  //删除开通数据
        AllwinStore::where($this->mini_program)->where(['id' => $id])->delete();   //删除好店
        return json(['code'=>200,'msg'=>'操作成功']);
    }

    /**
     * 选择所属用户
     */
    public function selectStoreManage(){
        $view['keyword'] = Request::param('keyword');
        $view['input']   = Request::param('input');
        $condition = [];
        if(!empty($view['keyword'])){
            if(Validate::isMobile($view['keyword'])){
                $condition[] = ['phone_uid','=',$view['keyword']];
            }else{
                $condition[] = ['nickname','like','%'.$view['keyword'].'%'];
            }
        }
        $agent_uid = AllwinUserAgent::where($this->mini_program)->column('uid');
        $view['list'] = SystemUser::where($this->mini_program)->where($condition)->whereNotIn('id',$agent_uid)->order('id desc')->paginate(10,false,['query' => ['input' => $view['input'],'keyword' => $view['keyword']]]);
        return view()->assign($view);
    }

    /**
     * 选择所属用户
     */
    public function isStoreManage(int $user_id){
        $worker = StoreWorker::where(['uid' => $user_id])->count();
        if($worker){
            return json(['code'=>0,'msg'=>'您已是某好店员工,禁止设置为老板']);
        }
        return json(['code'=>200,'msg'=>'允许选择']);
    }
    
    /**
     * 给好店添加管理员
     */
    public function winUser(int $store_id){
        if(request()->isAjax()){
            $ids = Request::param('ids/s');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要关联的优惠券']);
            }
            $uid = (array)ids($ids,true);
            $worker_uid = StoreWorker::where($this->mini_program)->where(['uid' => $uid])->column('uid'); //查询添加的用户是否在其它点做员工
            $uid = array_diff($uid,$worker_uid);//如果存在就去重
            $data = [];
            foreach ($uid as $key => $value) {
                $data[$key]['member_miniapp_id'] = $this->member_miniapp_id;
                $data[$key]['uid']               = $value;
                $data[$key]['store_id']          = $store_id;
            }
            $result = StoreWorker::insertAll($data);
            if($result){
                //批量添加的员工为当前店铺的会员
                foreach ($data as $key => $value) {
                    AllwinUser::editer($value['uid'],$value['store_id']);
                    //通知到申请者微信
                    Inform::sms($value['uid'],$this->member_miniapp_id,['title' =>'业务进展通知','type' => '身份变更','state' => '成功','content' =>'您的身份已变更为员工']);
                }
                return json(['code'=>200,'msg'=>'添加员工成功','data' =>[]]);
            }else{
                return json(['code'=>0,'msg'=>'添加员工失败']);
            }
        }else{
            //读好好店员工和好店老板的UID,做筛查排除
            $uid = StoreWorker::where($this->mini_program)->column('uid');       //好店员工
            $keyword  = Request::param('keyword');
            $condition  = [];
            $condition[] = ['id','NOT IN',$uid];
            if(!empty($keyword)){
                if(Validate::isMobile($keyword)){
                    $condition[] = ['phone_uid','=',$keyword];
                }else{
                    $condition[] = ['nickname','LIKE','%'.$keyword.'%'];
                }
            }
            $view['list']     = SystemUser::where($this->mini_program)->where($condition)->order('id desc')->paginate(20,false,['query' => ['store_id' => $store_id]]);
            $view['store_id'] = $store_id;
            $view['keyword']  = $keyword;
            return view()->assign($view);
        }
    }

    //删除员工
    public function delUser(int $id){
        $result = StoreWorker::where($this->mini_program)->where(['uid' => $id])->delete();
        if($result){
            //判断是否创客,如果是创客解除绑定关系
            $parent_vip = Vip::where(['user_id' => $id,'is_lock' => 0,'state' => 1])->field('vipcard_id,user_id')->count(); 
            if($parent_vip){
                AllwinUser::editer($id,0); //取消店铺关系
            }
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        } 
    }

     /**
     * 设置好店收银员
     * @param integer $id 用户ID
     */
    public function isCashier(int $id){
        $result = StoreWorker::setWorker($id,$this->member_miniapp_id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    }
    
    /**
     * 读取好店分类
     * @return void
     */
    public function storecate(int $cate_id){
        $cate = AllwinStoreCate::where(['member_miniapp_id' => $this->member_miniapp_id,'parent_id' => $cate_id])->field('id,name')->order('sort desc,id desc')->select(); 
        return json(['code'=>200,'msg'=>'成功','data' => $cate]);
    }
 
    /**
     *  根据地址位置转账
     * @return void
     */
    public function baidu($address){
        $view['address']  = $address;
        return view()->assign($view);
    }   

    /**
     *  根据地址位置读取地址
     * @return void
     */
    public function maps($address){
        $rel = AliApi::address($address);
        if(!$rel){
            return enjson(0,'请确认是否要帐号欠费');
        }
        $address = $rel['geocodes'][0];
        $location =  explode(',',$address['location']);
        return enjson(200,'成功',$location);
    }

    /**
     * 连锁门店
     */
    public function chainStore(){
        $store_id = $this->request->param('store_id/d');
        $view['lists']     = AllwinStoreChain::where(['store_id' => $store_id])->order('sort desc,id desc')->paginate(20);
        $view['store_id']  = $store_id;
        return view()->assign($view);
    }


    //编辑
    public function chainStoreEdit(int $store_id){
        if(request()->isAjax()){
            $data = [
                'id'                => Request::param('id/d',0),
                'store_id'          => $store_id,
                'code_id'           => Request::param('code_id/s'),
                'title'             => Request::param('title/s'),
                'address'           => Request::param('address/s'),
                'longitude'         => Request::param('longitude/s'),
                'latitude'          => Request::param('latitude/s'),
                'telphone'          => Request::param('telphone/s'),
                'update_time'       => time(),
                'member_miniapp_id' => $this->member_miniapp_id
            ];
            $validate = $this->validate($data,'Store.chain');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            //判断付款码
            $result = AllwinStore::where(['code_id' => $data['code_id']])->find();
            if($result){
                return enjson(0,'付款编码已存在');
            }else{
                $code_rel = AllwinStoreChain::where('id','<>',$data['id'])->where(['code_id' => $data['code_id']])->find();
                if($code_rel){
                    return enjson(0,'付款编码已存在');
                }
            }
            if($data['id']){
                $rel = AllwinStoreChain::update($data);
            }else{
                $rel = AllwinStoreChain::create($data);
            }
            if($rel){
                return json(['code'=>200,'url'=>url('store/chainStore',['store_id' => $store_id]),'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }else{
            $view['id']       = Request::param('id/d',0);
            $view['info']     = AllwinStoreChain::where(['store_id' => $store_id,'id' => $view['id']])->find();
            $view['store_id'] = $store_id;
            return view()->assign($view);
        }
    }

    //删除
    public function chainDelete(int $id){
        AllwinStoreChain::where($this->mini_program)->where(['id' =>$id])->delete();   //删除好店
        return json(['code'=>200,'msg'=>'操作成功']);
    } 

    /**
     * 门店排序
     */
    public function chainSort(){
        if(request()->isAjax()){
            $data = [
                'sort' => Request::param('sort/d'),
                'id'   => Request::param('id/d'),
            ];
            $validate = $this->validate($data,'Cate.sort');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result = AllwinStoreChain::where(['id' => $data['id']])->update(['sort' => $data['sort']]);
            if($result){
                return json(['code'=>200,'msg'=>'操作成功']);
            }else{
                return json(['code'=>0,'msg'=>'操作失败']);
            }
        }
    }



  /**
     * 判断商户是否重复
     * @return boolean
     */
    public function codeid(){
        $store_id = Request::param('store_id/d',0);
        $code_id  = Request::param('param/d');
        if(empty($code_id)){
            return json(['status'=>'n','info'=>'未输入付款编码']);
        }
        if(strlen($code_id) != 12){
            return json(['status'=>'n','info'=>'付款编码必须12位']);
        }
        if($store_id){
            $result = AllwinStore::where('id','<>',$store_id)->where(['code_id' => $code_id])->find();
        }else{
            $result = AllwinStore::where(['code_id' => $code_id])->find();
        }
        if($result){
            return json(['status'=>'n','info'=>'付款编码已存在']);
        }
        $rel = AllwinStoreChain::where(['code_id' => $code_id])->find();
        if($rel){
            return json(['status'=>'n','info'=>'付款编码已存在']);
        }
        return json(['status'=>'y','info'=>'付款编码可用']);
    }

    
    /**
     * 分类类型
     * @param integer $id 用户ID
     */
    public function chainType(int $id){
        $result = AllwinStoreChain::isType($id);
        if(!$result){
            return json(['code'=>0,'message'=>'操作失败']);
        }else{
            return json(['code'=>200,'message'=>'操作成功']);
        }
    } 

    /**
     * 判断商户是否重复
     * @return boolean
     */
    public function chainCodeid(){
        $chain_id = Request::param('chain_id/d',0);
        $code_id  = Request::param('param/d');
        if(empty($code_id)){
            return json(['status'=>'n','info'=>'未输入付款编码']);
        }
        if(strlen($code_id) != 12){
            return json(['status'=>'n','info'=>'付款编码必须12位']);
        }
        if($chain_id){
            $result = AllwinStoreChain::where('id','<>',$chain_id)->where(['code_id' => $code_id])->find();
        }else{
            $result = AllwinStoreChain::where(['code_id' => $code_id])->find();
        }
        if($result){
            return json(['status'=>'n','info'=>'付款编码已存在']);
        }
        $rel = AllwinStore::where(['code_id' => $code_id])->find();
        if($rel){
            return json(['status'=>'n','info'=>'付款编码已存在']);
        }
        return json(['status'=>'y','info'=>'付款编码可用']);
    }
}